package com.huluobo.a2205parkdemo.patrol

import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TimePicker
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2205parkdemo.R
import com.huluobo.a2205parkdemo.adapter.PointAdapter
import com.huluobo.a2205parkdemo.databinding.ActivityAddPatrolBinding
import com.huluobo.base.bean.PPointBean
import com.huluobo.base.bean.PPointBeanItem
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.StringBuilder
import java.util.Calendar

@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<ActivityAddPatrolBinding, PatrolVideModel>() {
    private lateinit var pointAdapter: PointAdapter

    private var startTime = 0L
    private var endTime = 0L
    private var time = 0L

    //上传巡逻路线需要的参数
    private var pEnd = ""
    private var pStart = ""
    private var pTime = ""
    private var pPoint = ""
    private var pGroupId = ""
    val newPointList = mutableListOf<PPointBeanItem>()


    private val calendar = Calendar.getInstance().apply {
        set(Calendar.HOUR, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    override fun initData() {
        vm.getAllPoint()
        vm.getAllPointSuccess.observe(this) {
            val list = Gson().fromJson(it, PPointBean::class.java)
            pointAdapter.data.clear()
            pointAdapter.data.addAll(list)
            pointAdapter.notifyDataSetChanged()
        }

        vm.addPatrolSuccess.observe(this){
            Log.i("TagA","添加巡逻路线成功:$it")
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

    override fun initView() {
        binding.addPatrolHeader.headerTitle.text = "添加巡更路线"
        binding.addPatrolHeader.headerBack.setOnClickListener { finish() }
        binding.addPatrolHeader.headerBack.visibility = View.VISIBLE

        binding.addPatrolRv.layoutManager = GridLayoutManager(this, 2)
        pointAdapter = PointAdapter()
        binding.addPatrolRv.adapter = pointAdapter

        binding.addPatrolStartTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                object : OnTimeSetListener {
                    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                        calendar.set(Calendar.MINUTE, minute)
                        startTime = calendar.timeInMillis
                        binding.addPatrolStartTimeNowTv.text = "$hourOfDay:$minute"
                        Log.i("TagA", "startTime:$startTime")
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true,
            ).show()
        }

        binding.addPatrolEndTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                object : OnTimeSetListener {
                    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                        calendar.set(Calendar.MINUTE, minute)
                        endTime = calendar.timeInMillis
                        Log.i("TagA", "endTime:${endTime}")
                        binding.addPatrolEndTimeNowTv.text = "$hourOfDay:$minute"
                        time = endTime - startTime
                        if (time <= 0 || startTime == 0L) {
                            ToastUtils.showLong("请重新选择时间")
                        } else {
                            val newTime = time / 1000 / 60 / 60
                            binding.addPatrolTimeNowTv.text = "${newTime}小时"
                        }
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true,
            ).show()
        }

        val pointListLiveData = MutableLiveData<List<PPointBeanItem>>()
        pointAdapter.setOnItemClickListener { adapter, view, position ->
//            val pPointBeanItem =
//                PPointBeanItem(pointAdapter.data[position].pointId, pointAdapter.data[position].pointName)
            val pPointBeanItem = pointAdapter.data[position]
            newPointList.add(pPointBeanItem)
            pointListLiveData.postValue(newPointList)
        }

        pointListLiveData.observe(this) {
            val points = StringBuilder()
            newPointList.forEach {
                points.append(it.pointName)
                points.append(",")
            }
            binding.addPatrolChoicePointResultTv.text = points.toString()
        }

        binding.addPatrolCommitBtn.setOnClickListener {
            pStart = binding.addPatrolStartTimeNowTv.text.toString()
            pEnd = binding.addPatrolEndTimeNowTv.text.toString()
            pTime = binding.addPatrolTimeNowTv.text.toString()
            pPoint = Gson().toJson(newPointList)

            if (pStart.isNotEmpty() && pEnd.isNotEmpty() && pTime.isNotEmpty() && pPoint.isNotEmpty()) {
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_PATROL_START] = pStart
                map[Const.PARAM_PATROL_END] = pEnd
                map[Const.PARAM_PATROL_TIME] = pTime
                map[Const.PARAM_PATROL_POINT] = pPoint
                map[Const.PARAM_PATROL_GROUP] = 48

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.addPatrol(body)
            }else{
                ToastUtils.showLong("有空的选项值")
            }
        }
    }
}